package middleware

import (
	"fmt"
	"gitee.com/git_public/vfaith/fount/handle"
	"log"
	"net/http"
)

func initEntityHandler(w http.ResponseWriter, r *http.Request) *handle.EntityHandler {
	return &handle.EntityHandler{
		BlendHttp: handle.NewBlendHttp(w, r),
	}
}

func HttpContextEntity(next func(handler *handle.EntityHandler) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		entityHandler := initEntityHandler(w, r)
		if entityHandler == nil {
			return
		}

		err := next(entityHandler)
		if err != nil {
			log.Print(err)
			http.Error(w, fmt.Sprintf("Internal Server Error：【%s】", err), http.StatusInternalServerError)
		}
	}
}

func HttpContextEntityNoError(next func(handler *handle.EntityHandler)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		entityHandler := initEntityHandler(w, r)
		if entityHandler == nil {
			return
		}

		next(entityHandler)
	}
}
